import React from "react";
import { Button, Form, Input, message } from "antd";
import { useNavigate, Navigate } from "react-router-dom";
import { getLogin } from "./../../service/index";
import "./index.less";

const Login = () => {
  const navigate = useNavigate();
  if (localStorage.getItem("token")) {
    return <Navigate to="/home" replace />;
    // navigate("/home");  // 这个为什么不可以？？？？？
  }
  const onFinish = ({ username, password }) => {
    if (!username || !password) {
      message.warning("用户名或者密码不能为空！");
    }
    getLogin()
      .then((res) => {
        const { token, username, authMenu } = res;
        localStorage.setItem("token", token);
        localStorage.setItem("username", username);
        localStorage.setItem("authMenu", JSON.stringify(authMenu));
        navigate("/home");
      })
      .catch((err) => {
        console.log(err);
      });
  };
  return (
    <div className="login-page">
      <Form
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        style={{
          maxWidth: 600,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            {
              required: true,
              message: "请输入用户名!",
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: "请输入密码!",
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};
export default Login;
